﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Client.Web.ParlInfoServiceReference;
using System.Linq.Dynamic;

namespace Client.Web
{

    public partial class LinqToOData : Page
    {
        private ParlInfoContainer _parlInfoEntities;

        protected void Page_Load(object sender, EventArgs e)
        {
            var start = DateTime.Now;

            /*
            //var context = new DataServiceContext(new Uri("http://p58300:3623/ParlInfoService.svc/"));
            _parlInfoEntities = new ParlInfoContainer(new Uri("http://parlinfotestservice.cloudapp.net/ParlInfoService.svc"));

            //var gsr = from GenericSearchResult g in _parlInfoEntities.GenericSearchResults
            //          //where g.Type == "Press Release"
            //          orderby g.Date descending
            //          select g;

            var gsr = _parlInfoEntities.GenericSearchResults.Where( g => g.Date > DateTime.Parse("1990-01-01"));
            gsr = gsr.OrderByDescending(g => g.Date);

            //foreach( var bill in bills.ToList() )
            //{
            //      Response.Write(String.Format("<p>Bill Title: {0} (Status: {1})</p>", bill.Title, bill.Status));
            //}
            //rptrGenericSearchResults.ItemTemplate = 
            lvGenericSearchResults.DataSource = gsr.Take(5);
            lvGenericSearchResults.DataBind();
            */
            ParlInfoContainer PI = new ParlInfoContainer(new Uri("http://parlinfotestservice.cloudapp.net/ParlInfoService.svc"));
            // search criteria via search panel
            string searchTerm = "S";
            bool titleOnlySearch = true;
            DateTime? dateFrom = DateTime.Parse("1900-01-01");
            DateTime? dateTo = DateTime.Parse("2010-11-01");
            int? parlNum = null;
            string status = "Before House of Representatives";
            string type = "Government"; //government/private

            var bills = PI.Bills.AsQueryable();

            if (!String.IsNullOrEmpty(searchTerm))
                if (titleOnlySearch)
                {
                    bills = bills.Where(b => b.Title.Contains(searchTerm));
                    bills = bills.Where(b => b.Title.Contains("b"));
                }
                else
                    bills = bills.Where(b => b.IndexedContent.Contains(searchTerm));

            //if (dateFrom != null && dateTo != null)
            //    bills = bills.Where(b => b.Date >= dateFrom && b.Date <= dateTo);
            if (parlNum != null)
                bills = bills.Where(b => b.ParliamentNumber == parlNum);
            if (!String.IsNullOrEmpty(status))
                bills = bills.Where(b => b.Status == status);
            if (!String.IsNullOrEmpty(type))
                bills = bills.Where(b => b.Type == type);

            bills = bills.OrderBy(b => b.Title); // or date, chamber etc, ascending/desc

            var billSearchResults = from b in bills
                                    select new
                                    {
                                        b.Id,
                                        b.Title,
                                        b.Date,
                                        Chamber = b.OriginatingChamber,
                                        b.Status,
                                        b.Portfolio,
                                        b.Sponsor,
                                        b.Summary,
                                        b.AsPassedHTMLLink,
                                        b.FirstReadingHTMLLink,
                                        b.ExplanatoryMemoranda
                                    };

            foreach (var Result in billSearchResults.ToArray())
            { 
                Response.Write("<p>" + Result.Title + "</p>");
                Response.Write("<p>" + Result.Date.ToLongDateString() + "</p>");
            }
              

            var finish = DateTime.Now;

            ltlServerName.Text = "Served from: " + System.Environment.MachineName + ", Linq query executed in " + (finish - start).ToString();
        }

        protected void GsrListView_ItemCreated(object sender, ListViewItemEventArgs e)
        {
            var item = e.Item as ListViewDataItem;
            var g = item.DataItem as GenericSearchResult;
            if (g == null)
                return;


            string url = "GenericItemTemplate.ascx";
            if (g.Type == "House Sitting")
                url = "HouseSittingItemTemplate.ascx";

            var lv = sender as GsrListView;
            lv.ItemTemplate = this.LoadTemplate(url);
        }

    }

    public class GsrListViewCreatingEventArgs : EventArgs
    {
        private int _dataItemIndex;
        private int _displayItemIndex;

        public GsrListViewCreatingEventArgs( int dataItemIndex, int displayItemIndex)
        {
            _dataItemIndex = dataItemIndex;
            _displayItemIndex = displayItemIndex;
        }

        public int DisplayIndex
        {
            get{ return _displayItemIndex; }
            set{ _displayItemIndex = value; }
        }
        public int DataItemIndex
        {
            get{ return _dataItemIndex; }
            set{ _dataItemIndex = value; }
        }
    }

    public class GsrListView : ListView
    {
        public event EventHandler<GsrListViewCreatingEventArgs> ItemCreating;

        private int _displayIndex;
        private bool _shouldInstantiate = false;

        protected override void InstantiateItemTemplate(Control container, int displayIndex)
        {
            if(_shouldInstantiate)
            {
                base.InstantiateItemTemplate(container, displayIndex);
                _shouldInstantiate = false;
            }
        }

        protected override ListViewDataItem  CreateDataItem(int dataItemIndex, int displayIndex)
        {
            // fire itemCreating
            if(ItemCreating != null)
            ItemCreating(this, new GsrListViewCreatingEventArgs(dataItemIndex, displayIndex));

            _displayIndex = displayIndex;

            return base.CreateDataItem(dataItemIndex, displayIndex);
        }

        protected override void  OnItemCreated(ListViewItemEventArgs e)
        {
 	         base.OnItemCreated(e);

                    _shouldInstantiate = true;
                    InstantiateItemTemplate(e.Item, _displayIndex);
        }
    }
}